package cn.maiyar.web.xss.filter;

import cn.maiyar.web.xss.wrapper.XssHttpServletRequestWrapper;
import cn.maiyar.web.xss.XssProperties;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.AllArgsConstructor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * XSS过滤
 *
 * @author c.c
 */
@AllArgsConstructor
public class XssFilter implements Filter {

    private XssProperties xssProperties;

    @Override
    public void init(FilterConfig config) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String path = ((HttpServletRequest) request).getServletPath();
        if (isSkip(path)) {
            chain.doFilter(request, response);
        } else {
            XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
            chain.doFilter(xssRequest, response);
        }
    }

    private boolean isSkip(String path) {
        return (xssProperties.getExcludePatterns().stream().anyMatch(path::startsWith))
                || (xssProperties.getSkipUrl().stream().map(url -> url.replace("/**", StringPool.EMPTY)).anyMatch(path::startsWith));
    }

    @Override
    public void destroy() {

    }
}
